package com.hub.videobrowsdownload

import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.util.Log
import android.webkit.SafeBrowsingResponse
import android.webkit.SslErrorHandler
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import java.net.URL

class BrowsMyWebviewClien(
    val webView: WebView,
    val tabWebViewModel: BrowsTabWebViewModel
) : WebViewClient() {

    override fun onLoadResource(view: WebView?, url: String?) {
        super.onLoadResource(view, url)
        var v = 0
        if (url.isNullOrEmpty()) {
            return
        }
        try {
            val uRL0 = URL(webView.getUrl());
            if (!uRL0.getHost().contains(".facebook.") && !uRL0.getHost()
                    .contains(".instagram.")
            ) {
                if (uRL0.getHost().contains(".google.")) {
                    return;
                }

                val z1 = uRL0?.getHost()?.contains(".youtube.");
                if (z1 == true) {
                    return
                } else {
                    v = 0
                }
            } else {
                v = 1
            }

        } catch (exception0: Exception) {
            v = 0
        }

        var v1 = 0
        val s1 = BrowsM3U8Helper.getUrlPath(url)
        if (v != 0 && ((s1.endsWith(".mp4")) || (s1.endsWith(".webm")) || (s1.endsWith(".ogg")))) {
            val urlLink: String? =
                if (!url.contains("&bytestart=") || !url.contains("&byteend=")) null else url.substring(
                    0,
                    url.indexOf("&bytestart=")
                ) + "&bytestart=0" + "&byteend=*"

            if (urlLink != null) {
                var mUrl = url
                if (mUrl.contains(".mp4")) {
                    v1 = mUrl.indexOf(".mp4") + 4
                    if (mUrl.length != v1) {
                        mUrl = mUrl.substring(0, v1)
                    }
                } else {
                    v1 = mUrl.indexOf(".webm") + 5
                    if (mUrl.length != v1) {
                        mUrl = mUrl.substring(0, v1)
                    }
                }
                val urlSha1 = BrowsHash256.toHash(mUrl)
                Log.i("src_mp4_loadres", urlLink)
                // TODO: GET MP4 URL
                BrowsM3U8Helper.findMP4Video(urlLink, tabWebViewModel)
                return
            }
        } else if (url.startsWith("https://") || url.startsWith("http://")) {
            if (s1.endsWith(".m3u8")) {

                val v2 = url.indexOf(".m3u8") + 5
                val s4 = BrowsHash256.toHash(if (v2 == url.length) url else url.substring(0, v2))
                Log.i("src_m3u8_loadres", url)
                // TODO: GET M3U8 URL
                BrowsM3U8Helper.findM3U8Video(url, tabWebViewModel)
                return
            }

            if ((s1.endsWith(".mp4")) || (s1.endsWith(".ogg")) || (s1.endsWith(".webm"))) {
                tabWebViewModel.findVideoSrc(url);
            }

        }
    }

    var lastPageFinishedTime = 0L
    override fun onPageFinished(view: WebView?, url: String?) {
        super.onPageFinished(view, url)
        if (!url.isNullOrEmpty() && !url.startsWith("about:")) {
            try {
                if (System.currentTimeMillis() - lastPageFinishedTime > 1500L) {
                    lastPageFinishedTime = System.currentTimeMillis()
                    // 上报url
                }
            } catch (unused_ex: java.lang.Exception) {
            }
            return
        } else {
            webView.clearHistory()
            webView.clearCache(true)
            // TODO: GO HOME
        }
    }

    override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
        super.onPageStarted(view, url, favicon)

        if (!url.isNullOrEmpty()) {
            tabWebViewModel.startNewUrl(url)
        }

        if ((url?.startsWith("https://") == true || url?.startsWith("http://") == true)) {
            webView.evaluateJavascript(
                "javascript:window.addEventListener(\"DOMContentLoaded\", (event) => {\n                            var arr = document.getElementsByTagName(\"video\");\n                           for(var i = 0;i < arr.length;i++){\n                                arr[i].setAttribute(\"preload\",\"auto\");                            }\n             });",
                null
            );
        }


    }

    override fun onReceivedSslError(
        view: WebView?,
        handler: SslErrorHandler?,
        error: SslError?
    ) {
        handler?.cancel()
    }

    override fun onSafeBrowsingHit(
        view: WebView?,
        request: WebResourceRequest?,
        threatType: Int,
        callback: SafeBrowsingResponse?
    ) {
        super.onSafeBrowsingHit(view, request, threatType, callback)
        if (Build.VERSION.SDK_INT >= 27) {
            callback?.showInterstitial(true);
        }
        Toast.makeText(
            webView.context,
            "Attention: Unsafe site detected. Exit immediately.",
            Toast.LENGTH_SHORT
        ).show()
    }

    override fun shouldOverrideUrlLoading(
        view: WebView?,
        request: WebResourceRequest?
    ): Boolean {
        if (request != null) {

            try {
                if (!request.getUrl().toString().startsWith("https://") && !request.getUrl()
                        .toString().startsWith("http://") && !request.getUrl().toString()
                        .startsWith("about:")
                ) {
                    return true;
                }

                val z = request.getUrl().getHost()?.contains(".youtube.") ?: false
                if (!z && (!request.getUrl().toString()
                        .startsWith("https://m.youtube.") && !request.getUrl().toString()
                        .startsWith("https://www.youtube."))
                ) {
                    return false;
                }else{
                    Toast.makeText(webView.context, "Doesn\'t support Youtube", Toast.LENGTH_LONG).show();
                }
            } catch ( unused_ex:Exception) {
                return false;
            }
        }
//            return super.shouldOverrideUrlLoading(view, request)
        return true
    }
}